<?php
// 本类由系统自动生成，仅供测试用途
class NewsAction extends Action {

    public function index(){
		exit;
		$this->display(); // 输出模板

    }

	//新闻列表
	public function lists(){
		$c = $this->_get('c');
		$Category =   M('Category');
		$oneArr = $Category->where("parentid = 10 AND catdir='$c'")->find();

		$catid = $oneArr['catid'];
		$catname = $oneArr['catname'];
		$caturl = $oneArr['url'];
		
		if($catid){
			Load('extend');
			$News =   M('News');
			import("ORG.Util.Page");// 导入分页类
			$p = $this->_get('p');
			$nowPage = isset($p)?$p:1;
			$where = "catid=$catid AND title!=''";
			$count      = $News->where($where)->count();// 查询满足要求的总记录数
			$Page       = new Page($count,130);// 实例化分页类 传入总记录数
			$list = $News->where($where)->order('id desc')->page($nowPage.','.$Page->listRows)->select();
			//特殊处理URL
			$Page->url = U('/'.$c.'/__PAGE__');
			$Page->kylingood = 1;
			$Page->rollPage = 5;
			$pageshow       = $Page->show();// 分页显示输出


			//精华推荐
			$goodArr = $News->query("SELECT `v9_news`.*,v9_position_data.* FROM `v9_news` 
left join `v9_position_data` on  `v9_news`.id=`v9_position_data`.id  WHERE  `v9_news`.title!='' AND v9_news.catid=$catid  AND  v9_position_data.posid IN (1,2,3,4,5,6,7,8,9,10)  order by `v9_news`.id desc limit 0,10");

			//热文排行
			$rankArr = $News->query("SELECT `v9_news`.* FROM `v9_news` WHERE `v9_news`.title!='' AND catid=$catid  ORDER BY `v9_news`.id DESC LIMIT 0 , 10");

			//图片列表
			$imgArr = $News->query("SELECT `v9_news`.* FROM `v9_news` WHERE `v9_news`.title!='' AND catid=$catid AND thumb!='' ORDER BY `v9_news`.id DESC LIMIT 0 , 4");

			//热门新闻
			$hotArr = $News->query("SELECT `v9_news`.*,v9_news.thumb as newsthumb,v9_position_data.* FROM `v9_news` 
left join `v9_position_data` on  `v9_news`.id=`v9_position_data`.id  WHERE  `v9_news`.title!='' AND v9_news.thumb!='' AND v9_position_data.posid in (1,2,3,4,5,6,7,8,9) order by `v9_news`.id desc limit 15,10");
			
			//热门产品
			$hotProduct = $News->query("SELECT * FROM `v9_product` WHERE title!='' AND thumb!=''ORDER BY id DESC LIMIT 0 , 10");
			
			
			$this->assign('goodArr',$goodArr);// 精华推荐
			$this->assign('rankArr',$rankArr);// 热文排行
			$this->assign('imgArr',$imgArr);// 图片列表
			$this->assign('hotArr',$hotArr);// 热门新闻
			$this->assign('hotProduct',$hotProduct);// 热门产品


			$this->assign('catname',$catname);// 栏目名
			$this->assign('caturl',$caturl);// 栏目链接地址
			$this->assign('page',$pageshow);// 赋值分页输出
			$this->assign('list',$list);// 赋值数据集


			//SEO相关
			$SEO['title'] = $catname.'-都市家建材网';
			$SEO['keywords'] =  $catname.',都市家建材网,建材新闻,建材资讯,建材政策法规';
			$SEO['description'] = '都市家建材网提供专业且全面的建材产品供求信息,主要信息包含:建材产品的报价,建材产品的品牌,建材产品的招商，加盟以及建材代理信息,为广大建材行业的个人与企业同行们，提供海量的建材信息与商机，努力打造成中国最全的建材种类行业门户网站.';

			$this->assign('SEO',$SEO);// SEO相关

			//导航
			$NAV_LIST = '<a href="http://www.dushijia.com" title="网站首页" target="_blank">网站首页</a> &gt; 
			<a href="http://news.dushijia.com" title="新闻频道" target="_blank">新闻频道</a> &gt; '.$catname;
			$this->assign('NAV_LIST',$NAV_LIST);

			$this->display(); // 输出模板
		}else{
			header("HTTP/1.0 404 Not Found");
			header('Location: http://www.dushijia.com/error/404.html');
			exit;
		}
	
	}

	public function show(){

		
		$id = $this->_get('id');
		
		$News =   M('News');
		$newsArr = $News->query("SELECT `v9_news`.*,`v9_news_data`.*, v9_category.catname,v9_category.url as caturl FROM `v9_news` 
left join `v9_news_data` on  `v9_news`.id=`v9_news_data`.id 
left join v9_category on `v9_news`.catid=`v9_category`.catid  where `v9_news`.id = $id");
		if(count($newsArr)){
			Load('extend');
			import("ORG.Util.Sphinxapi");// 导入Sphinx类
			import("ORG.Util.Pinyin");// 导入Pinyin类
			$title = $keyword = $newsArr[0]['title'];
			$keywords = $newsArr[0]['keywords'];
			$catid = $newsArr[0]['catid'];
			$catname = $newsArr[0]['catname'];
			$caturl = $newsArr[0]['caturl'];
			$inlink = $newsArr[0]['inlink'];
			$description = $newsArr[0]['description'];
			$relation = $newsArr[0]['relation'];//产品相关推荐
			$relation_product = $newsArr[0]['relation_product'];//产品相关推荐
			//去掉为0的ID，且把重复性的ID也去掉
			$relationArr = array_unique(array_filter(explode("|",$relation)));
			$relationProductArr = array_unique(array_filter(explode("|",$relation_product)));
			$newsArr[0]['description'] = $description =  addslashes(strip_tags($newsArr[0]['description']));
			
			Load('extend');
			if($description == ''){
				
				$newsArr[0]['description'] = $description = addslashes(msubstr(strip_tags($newsArr[0]['content']),0,310));

				$sql = "UPDATE `v9_news` SET description = '$description' WHERE `v9_news`.id=$id";
				$re = $News->query($sql);
				
			}
			$SeoDescription = $newsArr[0]['description'] = msubstr($description,0,310);
			
			
			$Pinyin = new Pinyin();
			//如果有关键词，则直接搜索
			$keywordArr = explode(" ",$keywords);
			$nums = count($keywordArr);
			if($keywords && $nums>1){
				foreach($keywordArr as $k=>$val){
					$pinyin = $Pinyin->get($val,'utf-8');
					$keywordList[$k]['name'] = $val;
					$keywordList[$k]['pinyin'] = $pinyin;
				}
			}
			
			//如果相关文章小于21篇，则重新取一次相关文章
			if(count($relationArr)<11 || $nums<=1){

				//这里是增加的搜索
				$sphinx = new SphinxClient();
				//$sphinx->SetServer('localhost','9312');
				$sphinx->SetServer('218.106.98.186','9312');
				$sphinx->SetConnectTimeout(1);
				
				$sphinx->SetLimits(0,20);

				$wordresult = $sphinx->query($keyword,'main');
				$sphinx->SetMatchMode(SPH_MATCH_EXTENDED);
				$sphinx->SetSortMode (SPH_SORT_EXPR,"@weight*50000+id+ln(inputtime)*100000" );
				$string='';


				
				//如果有2个关键词，则直接用现在的关键词搜索
				if($keywords && $nums>1){
					foreach($keywordArr as $k=>$val){
						$arrword[]='@title '.$val;
						$pinyin = $Pinyin->get($val,'utf-8');
						$keywordList[$k]['name'] = $val;
						$keywordList[$k]['pinyin'] = $pinyin;
						$seo_Arr[] = $val;
					}
					$string = implode(' | ',$arrword);
				
				}else{
				
					//查找标题有的关键词
					if(is_array($wordresult['words'])){
						foreach($wordresult['words'] as $key=>$val){
							$arrword[]='@title '.$key;
							
							$seo_Arr[] = $key;
							//把关键词按字符长度存为key
							$newarr[$key] = strlen($key);
						}
						$string = implode(' | ',$arrword);
					}else{
						$string='@title '.$keyword;
						
						$newarr[$keyword] = strlen($keyword);
						$seo_Arr[] = $keyword;
						
					}
					//按分词字节数排序，得到前5个分词词组
					
					//按数组key倒序排列
					arsort($newarr);
					//截取前5位关键词
					array_splice($newarr, 5);
					$keyArr = array_filter(array_keys($newarr));
					$keywords = addslashes(implode(' ',array_unique(array_splice($keyArr, 5))));
					unset($keywordList);
					if(is_array($keyArr))foreach($keyArr as $k=>$val){
						$pinyin = $Pinyin->get($val,'utf-8');
						$keywordList[$k]['name'] = $val;
						$keywordList[$k]['pinyin'] = $pinyin;
						$seo_Arr[] = $val;
					}
					
					if(count($keyArr) >0 ){
						$sql = "UPDATE `v9_news` SET `keywords` = '$keywords' WHERE `v9_news`.`id` ='$id'";
						$re = $News->query($sql);
					}
				}
				
				$result = $sphinx->query($string,'main');

				$TotalResult = $result['total_found'];
				
				
				if(is_array($result["matches"])){
					foreach ( $result["matches"] as $doc => $docinfo ) {
						$idarr[] = $doc;
					}

					$newresult = $sphinx->query($string,'productmain');
					foreach ( $newresult["matches"] as $doc => $docinfo ) {
						$productidarr[] = $doc;
					}	
					
					$relationids = implode('|',$idarr);//把相关新闻ID存入到数据库中
					$relation_product = implode('|',$productidarr);//把相关产品ID存入到数据库中
					$News->query("UPDATE v9_news_data  set relation='$relationids',relation_product='$relation_product'  where id =$id");
				}
				/*
				$options = array(
							'before_match'          => '<font color="red">',
							'after_match'           => '</font>',
							'chunk_separator'       => '',
							'limit'                 => 300,
							'around'                => 10,
				);
				
				foreach($list as $key=>$Arr){
					$height_title[0] = $Arr['title'];
					//$height_content[0] = strip_tags($Arr['content']);
					$words = $sphinx->BuildExcerpts ($height_title,'main', $keyword, $options );  
					//$contents = $sphinx->BuildExcerpts ($height_content,'main', $keyword, $options );  
					
					$list[$key]['name'] = $words[0];
					//$list[$key]['contenthtml'] = $contents[0];
				
				}
				*/
				
			}else{
				$idarr = $relationArr;
				$productidarr = $relationProductArr;
			}

			$ids = implode(',',$idarr);
			$list = $News->query("SELECT inputtime,title,url FROM `v9_news`  WHERE `v9_news`.title!='' AND `v9_news`.id IN ($ids) AND id !=$id");
			

			$productids = implode(',',$productidarr);
			$likeproductlist = $News->query("SELECT inputtime,title,url FROM `v9_product`  WHERE `v9_product`.title!='' AND  `v9_product`.id IN ($productids)");

			//精华推荐
			$goodArr = $News->query("SELECT `v9_news`.*,v9_position_data.* FROM `v9_news` 
left join `v9_position_data` on  `v9_news`.id=`v9_position_data`.id  WHERE  `v9_news`.title!='' AND v9_news.catid=$catid  AND v9_news.id !=$id AND  v9_position_data.posid IN (1,2,3,4,5,6,7,8,9,10)  order by `v9_news`.id desc limit 0,10");

			//热文排行
			$rankArr = $News->query("SELECT `v9_news`.* FROM `v9_news` WHERE `v9_news`.title!='' AND  catid=$catid  ORDER BY `v9_news`.id DESC LIMIT 0 , 10");

			//图片列表
			$imgArr = $News->query("SELECT `v9_news`.* FROM `v9_news` WHERE `v9_news`.title!='' AND  catid=$catid AND thumb!=''   ORDER BY `v9_news`.id DESC LIMIT 0 , 4");

			//热门新闻
			$hotArr = $News->query("SELECT `v9_news`.*,v9_news.thumb as newsthumb,v9_position_data.* FROM `v9_news` 
left join `v9_position_data` on  `v9_news`.id=`v9_position_data`.id  WHERE  v9_news.thumb!='' AND `v9_news`.title!='' AND  v9_position_data.posid in (1,2,3,4,5,6,7,8,9)  order by `v9_news`.id desc limit 15,10");


			//热门产品
			$hotProduct = array_slice($likeproductlist,0,10);


			$this->assign('goodArr',$goodArr);// 精华推荐
			$this->assign('rankArr',$rankArr);// 热文排行
			$this->assign('imgArr',$imgArr);// 图片列表
			$this->assign('hotArr',$hotArr);// 热门新闻
			$this->assign('hotProduct',$hotProduct);// 热门产品
			
			$this->assign('catid',$catid);
			$this->assign('keywordList',$keywordList);// 关键词
			$newsArr[0]['content'] = $this->_tagLink($newsArr[0]['content'],$keywordList);

			$this->assign('newsArr',$newsArr[0]);// 赋值数据集

			$this->assign('likeproductlist',array_slice($likeproductlist,10,-1));// 相似产品

			
			$this->assign('listlike',array_slice($list,0,10));
			$this->assign('list',array_slice($list,10,-1));// 赋值数据集


			//SEO相关
			if(is_array($seo_Arr)&&count($seo_Arr)){
				$keys = implode(',',array_unique($seo_Arr));
			}else{
				$keys = implode(',',array_unique($keywordArr));
			}

			

			$SEO['title'] = $title.'-'.$catname.'-都市家建材网';
			$SEO['keywords'] =  $keys.','.$catname.',都市家建材网,建材新闻,建材资讯,建材政策法规';
			$SEO['description'] = strip_tags(str_replace('"',' ',$SeoDescription)).'-都市家建材网,中国最全的建材种类行业门户网站.';

			$this->assign('SEO',$SEO);// SEO相关
			
			//导航
			$NAV_LIST = '<a href="http://www.dushijia.com" title="网站首页" target="_blank">网站首页</a> &gt; 
			<a href="http://news.dushijia.com" title="新闻频道" target="_blank">新闻频道</a> &gt; 
			<a href="'.$caturl.'" title="'.$catname.'" target="_blank">'.$catname.'</a> &gt; '.$title;
			$this->assign('NAV_LIST',$NAV_LIST);


			$this->display(); // 输出模板

		}else{
			header("HTTP/1.0 404 Not Found");
			header('Location: http://www.dushijia.com/error/404.html');
			exit;
		
		}
	
	}



	//改变标签关键字
	private function _tagLink($content,$posttags) {
		
		$match_num_from = 1;
		$match_num_to = 10; 
		//$posttags = get_the_tags();
		
		if ($posttags) {
			 //usort($posttags, "tag_sort");
			 foreach($posttags as $tag) {
				 $link = 'http://www.dushijia.com/tag/show/'.$tag['pinyin'].'_1_1_'.urlencode($tag['name']).'.shtml';
				 $keyword = $tag['name'];
				  
				 //连接代码
				 $cleankeyword = stripslashes($keyword);
				 $url = "<a href=\"$link\" title=\"".str_replace('%s',addcslashes($cleankeyword, '$'),'查看所有%s相关的信息')."\"";
				 $url .= ' target="_blank" class="tag_link"';
				 $url .= ">".addcslashes($cleankeyword, '$')."</a>";
				 $limit = rand($match_num_from,$match_num_to);
			
				//不连接的代码
				 $content = preg_replace( '|(<a[^>]+>)(.*)('.$ex_word.')(.*)(</a[^>]*>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
				
				//$content = preg_replace( '|(<img)(.*?)('.$ex_word.')(.*?)(>)|U'.$case, '$1$2%&&&&&%$4$5', $content);
				
				$cleankeyword = preg_quote($cleankeyword,'\'');
					$regEx = '\'(?!((<.*?)|(<a.*?)))('. $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
				$content = preg_replace($regEx,$url,$content,$limit);
				$content = str_replace( '%&&&&&%', stripslashes($ex_word), $content);
			 }
			
		 }
		return $content;
	}
	

}